<template>
  <el-main style="padding: 0px 20px">
    <el-row style="margin:20px 0px">
      <my-Search :inputNoOptionSpan="6" :searchWay="true" :inputPlaceholder="'订单号'" @onSearch="getSearchContent"></my-Search>
      <el-date-picker
        v-model="choiceDateTime"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="下单开始日期"
        end-placeholder="下单结束日期"
        :default-time="['00:00:00', '23:59:59']"
        align="right"
        @blur="choiceDate"
        @change="choiceDate"
        >
      </el-date-picker>
      <el-select style="margin-left:10px" v-model="choiceType" multiple placeholder="全部订单类型" @change="typeSearch" collapse-tags clearable>
        <el-option
          v-for="(item,index) in searchType"
          :key="index"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button icon="el-icon-refresh-left" style="margin-left:10px" type="primary" @click="getUserOrders">刷新</el-button>
      <el-button v-if="showCancelOrders()" type="danger" icon="el-icon-close"  @click="cancelOrders" >取消订单</el-button>
      <el-button v-if="this.currentRow&&this.currentRow!=-1&&this.currentRow.orders.status==0" type="success" icon="el-icon-wallet"  @click="giveOrdersInfo" >支付订单</el-button>
    </el-row>
    <el-table
      :height="tableHeight"
      :data="ordersListDate"

      highlight-current-row
      @current-change="handleCurrentChange"
      ref="ordersTableRef"
      :row-class-name="isShowExpend"
    >
    <!-- row-key="orders.id" -->
      <el-table-column type="expand" width="55">
        <template slot-scope="scope">
            <el-row class="itemBox" v-if="scope.row.orders.type == 0">
              <el-col class="item" :span="11" v-for="item in scope.row.fieldBookList" :key="item.id">
                <el-row>
                  <el-col :span="5">
                    <el-image style="width: 120px; height: 120px" :src="item.cover" fit="fit" />
                  </el-col>
                  <el-col :span="14" :offset="1">
                    <el-descriptions size="small" :title="item.name" :column="2">
                        <el-descriptions-item label="费用">{{item.bookCost}} 元</el-descriptions-item>
                        <el-descriptions-item label="状态" >
                          <el-tag size="mini" :type="bookStatusArr[item.status].type" effect="plain">{{bookStatusArr[item.status].text}}</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="负责人">{{item.fieldUsername||'-'}}</el-descriptions-item>
                        <el-descriptions-item label="联系电话">{{item.fieldPhone||'-'}}</el-descriptions-item>
                        <el-descriptions-item label="场馆地址" :span="2">{{item.locate}}</el-descriptions-item>
                        <el-descriptions-item label="预约备注" :span="2">{{item.remark||'-'}}</el-descriptions-item>
                        <el-descriptions-item label="预约时间段" :span="2">{{item.startTime+"~"+item.endTime.split(' ')[1]}}</el-descriptions-item>
                        <el-descriptions-item label="申请预约时间" :span="2">{{item.createTime}}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                </el-row>
                <el-row style="text-align: right;">
                  <el-button v-if="item.status==1" type="primary" size="mini" @click="showCode(item.code,item.id,0)">入场码</el-button>
                  <el-button v-if="item.status==0||item.status==1" type="danger" size="mini" @click="cancelBook(item)">取消预约</el-button>
                </el-row>
              </el-col>
            </el-row>
            <el-row class="itemBox" v-else-if="scope.row.orders.type == 1">
              <el-col class="item" :span="11" v-for="item in scope.row.equipmentRentList" :key="item.id">
                <el-row>
                  <el-col :span="5">
                    <el-image style="width: 120px; height: 120px" :src="item.cover" fit="fit" />
                  </el-col>
                  <el-col :span="14" :offset="1">
                    <el-descriptions size="small" :title="item.name" :column="2">
                        <el-descriptions-item label="租借数量" >{{item.number}}</el-descriptions-item>
                        <el-descriptions-item label="租借时长">{{item.times | showTime}}</el-descriptions-item>
                        <el-descriptions-item label="价格">{{item.rentCost+' 元/时'}}</el-descriptions-item>
                        <el-descriptions-item label="价格小计">{{item.cost}} 元</el-descriptions-item>
                        <el-descriptions-item label="状态" >
                          <el-tag size="mini" :type="rentStatusArr[item.status].type" effect="plain">{{rentStatusArr[item.status].text}}</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="领取地址" :span="2">{{item.local}}</el-descriptions-item>
                        <el-descriptions-item label="租借时间" :span="2">{{item.getTime+'~'+item.backTime}}</el-descriptions-item>
                        <el-descriptions-item v-if="item.status==3||item.status==4" label="归还时间" :sapn="2">{{item.updateTime}}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                </el-row>
                <el-row style="text-align: right;">
                  <el-button v-if="item.status==1" type="primary" size="mini" @click="showCode(item.code,item.id,1)">租借码</el-button>
                  <el-button v-if="item.status==0||item.status==1" type="danger" size="mini" @click="cancelRent(item)">取消租借</el-button>
                  <el-button v-if="item.status==9" type="warning" size="mini" @click="payOutTimeOrdersInfo(item)">支付超时费用</el-button>
                </el-row>
              </el-col>
            </el-row>
            <el-row class="itemBox" v-else-if="scope.row.orders.type == 2">
              <el-col class="item" :span="7" v-for="item in scope.row.equipmentBuyList" :key="item.id">
                <el-row>
                  <el-col :span="9">
                    <el-image style="width: 100px; height: 100px" :src="item.cover" fit="fit" />
                  </el-col>
                  <el-col :span="14" :offset="1">
                    <el-descriptions size="small" :title="item.name" :column="2">
                        <el-descriptions-item label="购买数量" >{{item.number}}</el-descriptions-item>
                        <el-descriptions-item label="单价" >{{item.buyCost}} 元</el-descriptions-item>
                        <el-descriptions-item label="价格小计">{{item.cost}} 元</el-descriptions-item>
                        <el-descriptions-item label="状态" >
                          <el-tag size="mini" :type="buyStatusArr[item.status].type" effect="plain">{{buyStatusArr[item.status].text}}</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="领取地址" :span="2">{{item.local}}</el-descriptions-item>
                        <el-descriptions-item v-if="item.status==2||item.status==6" label="领取时间" :sapn="2">{{item.updateTime}}</el-descriptions-item>
                        <el-descriptions-item v-else-if="item.status==3" label="退货时间" :sapn="2">{{item.updateTime}}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                </el-row>
                <el-row style="text-align: right;">
                  <el-button v-if="item.status==1" type="primary" size="mini" @click="showCode(item.code,item.id,2)">领取码</el-button>
                  <el-button v-if="item.status==0||item.status==1" type="danger" size="mini" @click="cancelBuy(item)">取消交易</el-button>
                  <el-button v-if="item.status==2" type="danger" size="mini" @click="applyBack(item)">申请退货</el-button>
                </el-row>
              </el-col>
            </el-row>
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单编号" show-overflow-tooltip>
        <template slot-scope="scope">
          {{scope.row.orders.no}}
          <i class="el-icon-document-copy copyIcon" @click="copyOrderNo(scope.row.orders.no,$event)"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单内容" show-overflow-tooltip>
        <template slot-scope="scope">
          {{showOrdersContent(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column width="100px" align="right" label="实付金额">
        <template slot-scope="scope">
          {{scope.row.orders.cost | showCost(scope.row.orders.type)}}
        </template>
      </el-table-column>
      <el-table-column width="90px"  prop="orders.point" align="center" label="使用积分"></el-table-column>
      <el-table-column width="130px" align="center" label="订单类型">
        <template slot-scope="scope">
          {{searchType[scope.row.orders.type].label}}
        </template>
      </el-table-column>
      <el-table-column width="180px" prop="orders.createTime" align="center" label="下单时间"></el-table-column>
      <el-table-column
        align="center"
        label="订单状态"
        width="130px"
        prop="status"
        :filters="statusArr"
        :filter-method="statusFilterHandler"
      >
        <template slot-scope="scope">
            <el-alert
              :title="scope.row.orders.status | rentStatus(true,statusArr)"
              :type="scope.row.orders.status | rentStatus(false,statusArr)"
              show-icon
              :closable="false"
            />
        </template>
      </el-table-column>


    </el-table>
    <!-- 分页区 -->
    <pagination
    ref="pagination"
    @pagination="getPagination"
    :total="parseInt(totalPage)"
    :page="parseInt(searchCondition.page)"
    :limit="parseInt(searchCondition.pageSize)"
    :pageSizes="paginationSize"
    ></pagination>

    <el-dialog :title="codeTitle" :visible.sync="codeDialogVisible" width="300px" :show-close="false" center>
      <h1 style="color:#409EFF;letter-spacing: 10px;">{{code}}</h1>
      <vue-qr :logoSrc="$store.getters.avatar || ''" :text="JSON.stringify({id:codeId,code})" :size="200"></vue-qr>
    </el-dialog>
  </el-main>
</template>

<script>
import { editBookFieldStatusApi } from "@/api/fieldBook";
import { editBuyStatusApi, editRentStatusApi } from "@/api/equipment";
import { getUserOrdersApi,cancelOrderApi } from "@/api/orders";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
import clip from '@/utils/clipboard';
import vueQr from 'vue-qr'
  export default {
    components: {  mySearch, pagination,vueQr},
    data(){
      return{
        codeDialogVisible:false,
        codeTitle:'',
        codeId:'',
        code:'',
          bookStatusArr:[
          {text: '待支付', value: 0,type:'info'},
          {text: '待进场', value: 1,type:'warning'},
          {text: '已进场', value: 2,type:'success'},
          {text: '已取消', value: 3,type:'info'},
          {text: '管理员撤销', value: 4,type:'info'},
          {text: '已失效', value: 5,type:'info'},
          {text: '已过期', value: 6,type:'danger'}
        ],
        rentStatusArr:[
          {text: '待支付', value: 0,type:'info'},
          {text: '待领取', value: 1,type:'warning'},
          {text: '租借使用中', value: 2,type:'warning'},
          {text: '已按时归还', value: 3,type:'success'},
          {text: '超时归还', value: 4,type:'success'},
          {text: '已失效', value: 5,type:'info'},
          {text: '已超时', value: 6,type:'danger'},
          {text: '已取消', value: 7,type:'info'},
          {text: '管理员撤销', value: 8,type:'info'},
          {text: '待支付超时费用', value: 9,type:'warning'},
          {text: '已支付超时费用', value: 10,type:'warning'},
        ],
        buyStatusArr:[
          {text: '待支付', value: 0,type:'info'},
          {text: '待领取', value: 1,type:'warning'},
          {text: '已领取', value: 2,type:'success'},
          {text: '已退货', value: 3,type:'danger'},
          {text: '已失效', value: 4,type:'info'},
          {text: '申请退货中', value: 5,type:'warning'},
          {text: '已领取', value: 6,type:'success'},
          {text: '已取消', value: 7,type:'info'},
          {text: '管理员撤销', value: 8,type:'info'}
        ],

        statusArr:[
          {text: '未支付', value: 0,type:'warning'},
          {text: '已支付', value: 1,type:'success'},
          {text: '已关闭', value: 2,type:'info'},
        ],
        ordersListDate:[],
        tableHeight:0,
        currentRow:'',
        searchCondition :{
          uid: this.$store.getters.userId,
          no:'',
          type:'',
          startTime:'',
          endTime:'',
          page: 1,
          pageSize: 10,
        },
        choiceType:[],
        //筛选项
        searchType:[{label:"预约场馆",value:0},{label:"租借器材",value:1},{label:"购买器材",value:2},{label:"租借超时",value:3},{label:"充值金额",value:4}],
        //分页容量
        paginationSize: [5,10,20,30,50],
        //查询返回 总记录数
        totalPage: 0,
        choiceDateTime:'',
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一周',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一个月',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近半年',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      }
    },
    created(){
      this.getUserOrders();
    },
    mounted() {
      this.$nextTick(() => {
        //有页码区就高度多-120
        this.tableHeight = window.innerHeight - 323 - 120;
      })
    },
    methods:{
      //传递超时订单信息
      payOutTimeOrdersInfo(outTimeOrders){
        this.$emit("getOrdersInfo",outTimeOrders)
      },
      //传递订单信息
      giveOrdersInfo(){
        let payOrders = this.currentRow.orders;
        let parm = {
          oid:payOrders.id,
          no:payOrders.no,
          ordersCost:payOrders.cost,
          point:payOrders.point,
          type:payOrders.type,
          ordersStatus:payOrders.status,
          ordersVersion:payOrders.version,
          uid:payOrders.uid,
          ordersTime:payOrders.createTime
        }
        this.$emit("getOrdersInfo",parm)
      },
      //取消预约
      async cancelBook(row){
        let confirm = await this.$myconfirm("确定取消预约吗？");
        if (confirm) {
          let parm ={
            id:row.id,
            oid:row.oid,
            status: 3,
            version: row.version
          }
          let res = await editBookFieldStatusApi(parm);
          if(res&&res.code==200){
            this.$message.success(res.msg);
            this.getUserOrders();
          }
        }
      },

      //取消租借
      async cancelRent(row){
        let confirm = await this.$myconfirm("确定取消租借吗？");
        if (confirm) {
          let parm ={
            id:row.id,
            oid:row.oid,
            eid:row.eid,
            number:row.number,
            status: 7,
            version: row.version
          }
          let res = await editRentStatusApi(parm);
          if(res&&res.code==200){
            this.$message.success(res.msg);
            this.getUserOrders();
          }
        }
      },

      //取消提示
      async cancelBuy(row){
        let confirm = await this.$myconfirm("确定取消交易吗？");
        if (confirm) {
          this.changeBuyStatus(row,7);
        }
      },
      //购买器材申请退货
      async applyBack(row){
        let confirm = await this.$myconfirm("确定申请退货吗？");
        if (confirm) {
          this.changeBuyStatus(row,5)
        }
      },
      //更改购买状态记录
      async changeBuyStatus(row,statusCode){
        let parm ={
          id:row.id,
          oid:row.oid,
          eid:row.eid,
          number:row.number,
          status: statusCode,
          version: row.version
        }
        let res = await editBuyStatusApi(parm);
        if(res&&res.code==200){
          this.$message.success(res.msg);
          this.getUserOrders();
        }
      },
      //显示码
      showCode(code,id,type){
        this.code = code;
        this.codeId = id;
        if(type==0){
          this.codeTitle = '入场码';
        }else if(type==1){
          this.codeTitle = '租借码';
        }else if(type==2){
          this.codeTitle = '领取码'
        }
        this.codeDialogVisible = true;
      },

      //是否显示取消订单
      showCancelOrders(){
        if(this.currentRow&&this.currentRow!=-1&&this.currentRow.orders.status!=2){
          let flag = true;
          switch (this.currentRow.orders.type) {
            case 0:
              this.currentRow.fieldBookList.some(item=>{
                if(item.status==2||item.status==6){
                  flag = false;
                  return true;
                }
              })
              return flag;
            case 1:
              if(this.currentRow.equipmentRentList[0].status==0||this.currentRow.equipmentRentList[0].status==1){
                return true;
              }
              return false;
            case 2:
              this.currentRow.equipmentBuyList.some(item=>{
                if(item.status==2||item.status==5||item.status==6){
                  flag = false;
                  return true;
                }
              })
              return flag;
            default:
              return false;
          }
        }else{
          return false;
        }
      },
      //取消订单
      async cancelOrders(){
        let confirm = await this.$myconfirm("确定取消订单吗？");
        if (confirm) {
          if(this.currentRow&&this.currentRow.orders.type!=3&&this.currentRow.orders.type!=4){
            let res = await cancelOrderApi(this.currentRow.orders);
            if(res&&res.code==200){
              this.$message.success(res.msg);
            }
          }
          this.getUserOrders();
        }
      },
      //选中的租借信息
      handleCurrentChange(val) {
        this.currentRow = val;
      },
      //订单内容简介
      showOrdersContent(row){
          switch (row.orders.type) {
            case 0:
              if(row.fieldBookList.length>1){
                return `预约${row.fieldBookList[0].name}等${row.fieldBookList.length}个场次`;
              }else{
                return `预约${row.fieldBookList[0].name}`;
              }
              break;
            case 1:
                return `租借${row.equipmentRentList[0].name}×${row.equipmentRentList[0].number} ${this.showTime(row.equipmentRentList[0].times)}`;
              break;
            case 2:
              if(row.equipmentBuyList.length>1){
                return `购买${row.equipmentBuyList[0].name}×${row.equipmentBuyList[0].number} 等${row.equipmentBuyList.length}个器材`;
              }else{
                return `购买${row.equipmentBuyList[0].name}×${row.equipmentBuyList[0].number}`;
              }
              break;
            case 3:
              return '支付超时费用';
              break;
            case 4:
              return '充值金额';
              break;
            default:
              break;
          }
      },
      //租借时间计算
      showTime(val){
        if(val>=24){
          let t = val%24;
          let d = Math.floor(val/24);
          if(t!=0){
            return d+'天 '+t+'小时'
          }else{
            return d+'天'
          }
        }else{
          return val+'小时'
        }
      },
      //复制订单号
      copyOrderNo(text, event) {
        clip(text, event)
      },
      //日期范围查询
      choiceDate(){
        if(this.choiceDateTime!=null){
          this.searchCondition.startTime = this.choiceDateTime[0];
          this.searchCondition.endTime = this.choiceDateTime[1];
        }else{
          this.searchCondition.startTime = '';
          this.searchCondition.endTime = '';
        }
        this.getUserOrders();
      },
      //类型查询
      typeSearch(){
        this.searchCondition.type = this.choiceType.toString();
        this.getUserOrders();
      },
      //订单号查询
      getSearchContent(val){
        this.searchCondition.no = val;
        this.getUserOrders();
      },
      //分页查询
      getPagination(val){
        this.searchCondition.page = val.page;
        this.searchCondition.pageSize = val.limit;
        this.getUserOrders();
      },
      //查询
      async getUserOrders(){
        let res = await getUserOrdersApi(this.searchCondition);
        if(res&&res.code==200){
          this.ordersListDate = res.data.list;
          this.totalPage = res.data.total;
          this.handleCurrentChange();
        }
      },
      cancelRowColor(){
        this.$refs.ordersTableRef.setCurrentRow(-1);
      },
      //表格预约状态过滤
      statusFilterHandler(value, row, column){
        const property = column['property'];
        return row.orders[property] === value;
      },
      //隐藏展开行
      setClassName({row, index}){
      },
      isShowExpend ({row, index}) {
        if (row.orders.type==3||row.orders.type==4) {
          return 'hide-expend'
        }
        return ''
      }

    },
    filters:{
      rentStatus(val,flag,arr){
        if(flag){
          return arr[val].text
        }else{
          return arr[val].type
        }
      },
      showCost(val,type){
        if(val==0) {
          return '0 元'
        }else{
          if(type!=4){
            return '-'+val+' 元'
          }else{
            return '+'+val+' 元'
          }

        }
      },
      showTime(val){
        if(val>=24){
          let t = val%24;
          let d = Math.floor(val/24);
          if(t!=0){
            return d+' 天 '+t+' 小时'
          }else{
            return d+' 天'
          }
        }else{
          return val+' 小时'
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .copyIcon{
    font-size: 16px;
    color:#409EFF;
    cursor: pointer;
    &:hover{
      font-weight: bold;
      text-decoration:underline;
    }
  }
  .itemBox{
    margin:0 20px !important;
      .item{
        margin: 20px;
        padding: 20px 10px 10px 20px;
        min-height: 150px;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
        overflow: hidden;
      }
  }
  ::v-deep .el-dialog__body{
    text-align: center;
  }
  ::v-deep .hide-expend .el-table__expand-icon {
    display: none;
  }

</style>
